package com.tlgen.orm.utils.orm;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.tlgen.orm.components.rest.model.RequestMethodAndUrl;
import com.tlgen.orm.model.Model;
import com.tlgen.orm.model.PageResult;
import com.tlgen.orm.model.DataResult;
import com.tlgen.orm.param.FieldParam;
import com.tlgen.orm.support.QueryOperator;
import com.tlgen.orm.utils.reflect.ReflectionUtils;
import com.tlgen.orm.utils.http.HttpUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ConcurrentReferenceHashMap;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.tlgen.orm.constant.HttpConstant.APPLICATION_JSON;
import static com.tlgen.orm.constant.HttpConstant.ORIGINAL_REQUEST_URI;
import static com.tlgen.orm.constant.QueryOperatorConstant.*;
import static com.tlgen.orm.utils.ClassesUtils.*;
import static com.tlgen.orm.utils.reflect.ReflectionUtils.invokeHttpRequest;
import static com.tlgen.orm.utils.StringUtils.uncapUnderline;
import static com.tlgen.orm.utils.http.HttpUtils.getRequestFieldParams;
import static com.tlgen.orm.utils.http.HttpUtils.getRequestJson;
import static com.tlgen.orm.utils.orm.ORMUtils.getAllFields;
import static com.tlgen.orm.utils.orm.ORMUtils.getPrimaryKeyField;

/**
 * 高性能零代码处理工具（安全+性能优化版）
 */
@Slf4j
public class FastModeUtils {

    private static final ConcurrentMap<String, DateTimeFormatter> FORMATTER_CACHE = new ConcurrentHashMap<>();
    private static final ConcurrentMap<Class<?>, ThreadLocal<SimpleDateFormat>> DATE_FORMATTER_CACHE = new ConcurrentHashMap<>();

    // ==================== 操作类型枚举（安全+可读） ====================
    @Getter
    public enum OperationType {
        // 查询操作
        SELECT_BY_ID("通过ID查询单条记录"),
        SELECT_ONE("条件查询单条记录"),
        SELECT_PAGE("分页查询记录"),
        SELECT_CURSOR_PAGE("游标分页查询记录"),
        SELECT_LIST("查询记录列表"),

        // 修改操作
        SAVE("新增记录"),
        SAVE_BATCH("批量新增记录"),
        UPDATE("更新记录"),
        UPDATE_BATCH("批量更新记录"),
        UPDATE_SELECTIVE("选择性更新记录"),

        // 删除操作
        DELETE("删除记录"),
        DELETE_BY_ID("通过ID删除记录"),
        DELETE_BY_IDS("通过ID批量删除记录"),
        DELETE_LOGICAL_BY_ID("通过ID逻辑删除记录"),

        // 扩展API
        EXTEND_API("扩展API（GET）"),
        EXTEND_API_POST("扩展API（POST/PUT/DELETE）");

        private final String description;

        OperationType(String description) {
            this.description = description;
        }

    }

    // ==================== 路径到操作类型映射（高性能查找） ====================
    private static final ImmutableMap<String, OperationType> PATH_OPERATIONS = ImmutableMap.<String, OperationType>builder()
            .put("/selectById", OperationType.SELECT_BY_ID)
            .put("/selectOne", OperationType.SELECT_ONE)
            .put("/selectPage", OperationType.SELECT_PAGE)
            .put("/selectCursorPage", OperationType.SELECT_CURSOR_PAGE)
            .put("/select", OperationType.SELECT_LIST)
            .put("/deleteLogicalById", OperationType.DELETE_LOGICAL_BY_ID)
            .put("/deleteById", OperationType.DELETE_BY_ID)
            .put("/deleteByIds", OperationType.DELETE_BY_IDS)
            .put("/delete", OperationType.DELETE)
            .put("/updateSelective", OperationType.UPDATE_SELECTIVE)
            .put("/update", OperationType.UPDATE)
            .put("/updateBatch", OperationType.UPDATE_BATCH)
            .put("/save", OperationType.SAVE)
            .put("/saveBatch", OperationType.SAVE_BATCH)
            .build();

    // ==================== 缓存优化（减少反射开销） ====================
    private static final Map<String, Class<?>> MODEL_CLASS_CACHE = new ConcurrentHashMap<>(256);
    private static final Map<String, RequestMethodAndUrl> API_URL_CACHE = new ConcurrentHashMap<>(128);
    private static final Map<Class<?>, Map<String, Field>> FIELD_CACHE = new ConcurrentReferenceHashMap<>(512);

    // ==================== 常量定义（避免重复创建） ====================
    private static final String SELECT_BY_ID_PATH = "/selectById";


    /**
     * 零代码入口（安全+高性能）
     */
    public static DataResult processFastMode(HttpServletRequest request) {
        final String method = request.getMethod().toUpperCase();

        // 使用switch优化性能
        switch (method) {
            case "GET":
                return handleGetRequest(request);
            case "POST":
            case "PUT":
            case "DELETE":
                return handleModifyRequest(request);
            default:
                throw new RuntimeException("不支持的HTTP方法: " + method);
        }

    }

    /**
     * 处理GET请求（高性能优化）
     */
    private static DataResult handleGetRequest(HttpServletRequest request) {
        final String url = (String) request.getAttribute(ORIGINAL_REQUEST_URI);
        final PathMatchResult match = findPathMatch(url);

        // 使用枚举提高可读性
        if (match.operation != OperationType.EXTEND_API) {
            return processBaseQuery(request, match);
        }
        return processExtendedApi(request, url);
    }

    /**
     * 处理修改请求（安全+高性能）
     */
    private static DataResult handleModifyRequest(HttpServletRequest request) {
        final String url = (String) request.getAttribute(ORIGINAL_REQUEST_URI);
        final PathMatchResult match = findPathMatch(url);

        // 使用枚举提高可读性
        if (match.operation != OperationType.EXTEND_API_POST) {
            return processBaseModification(request, match);
        }
        return processExtendedApi(request, url);
    }

    // ==================== 辅助类和方法 ====================

    /**
     * 路径匹配结果（线程安全）
     */
    @Getter
    private static class PathMatchResult {
        final int index;
        final OperationType operation;

        PathMatchResult(int index, OperationType operation) {
            this.index = index;
            this.operation = operation;
        }
    }

    /**
     * 高性能路径匹配（O(1)复杂度）
     */
    private static PathMatchResult findPathMatch(String url) {
        // 使用流式处理优化查找
        AtomicReference<PathMatchResult> result = new AtomicReference<>(
                new PathMatchResult(-1, OperationType.EXTEND_API)
        );

        PATH_OPERATIONS.entrySet().parallelStream()
                .filter(entry -> {
                    if (url.contains(entry.getKey())) {
                        String[] split = url.split("/");
                        for (int i = split.length - 1; i >= 0; i--) {
                            if (Objects.equals("/".concat(split[i]), entry.getKey())) {
                                return true;
                            }
                        }
                    }
                    return false;
                })
                .findFirst()
                .ifPresent(entry -> {
                    int index = url.indexOf(entry.getKey());
                    result.set(new PathMatchResult(index, entry.getValue()));
                });

        return result.get();
    }

    /**
     * 处理基础查询（安全+高性能）
     */
    private static DataResult processBaseQuery(HttpServletRequest request, PathMatchResult match) {
        DataResult result = new DataResult();

        if (match.index == -1) {
            return result;
        }

        final String url = (String) request.getAttribute(ORIGINAL_REQUEST_URI);
        final String className = extractClassName(url.substring(0, match.index));
        final String fullClassName = getCachedClassName(className);

        // 安全校验：类名是否有效
        if (StrUtil.isBlank(fullClassName)) {
            return result;
        }

        final List<FieldParam> params = getRequestFieldParams(request);
        final String id = extractIdFromUrl(url, match.operation);

        // 构建安全查询条件
        final Class<?> modelClass = getCachedModelClass(fullClassName);
        List<FieldParam> queryFieldParams = HttpUtils.getQueryRequestFieldParams(params, modelClass);
        final QueryOperator query = buildSafeQueryOperator(queryFieldParams, match.operation);

        // 执行查询操作
        Object data = executeQueryOperation(match.operation, query, modelClass, params, id);
        result.setData(data);
        return result;
    }

    /**
     * 处理基础修改操作（增强版：支持路径ID操作）
     */
    private static DataResult processBaseModification(HttpServletRequest request, PathMatchResult match) {
        DataResult result = new DataResult();

        if (match.index == -1) return result;

        final String uri = request.getRequestURI();
        final String className = extractClassName(uri.substring(0, match.index));
        final String fullClassName = getCachedClassName(className);

        if (StrUtil.isBlank(fullClassName)) return result;

        // 获取模型类（带缓存）
        final Class<?> modelClass = MODEL_CLASS_CACHE.computeIfAbsent(fullClassName,
                ReflectionUtils::getClassByCompleteClassName);

        // 检查是否 xxxById 操作
        OperationType finalOperation = match.operation;
        Object operationData = null;

        // 1. 处理路径ID操作（高性能解析）
        if (match.getOperation() == OperationType.SELECT_BY_ID || match.getOperation() == OperationType.DELETE_BY_ID) {
            try {
                // 从路径中提取ID值（最后一段）
                String[] pathSegments = uri.split("/");
                String id = pathSegments[pathSegments.length - 1];
                String uriSuffix = pathSegments[pathSegments.length - 2];
                // 识别实际操作类型
                if (Objects.equals("deleteById", uriSuffix)) {
                    finalOperation = OperationType.DELETE_BY_ID;
                    Model.deleteById(id, modelClass);
                } else if (Objects.equals("selectById", uriSuffix)) {
                    Model.selectById(id, modelClass);
                }
            } catch (Exception e) {
                log.error("路径ID操作解析失败: {}", uri, e);
            }
        }
        // 2. 正常请求体操作
        else {
            operationData = parseRequestPayload(request, modelClass);
        }

        // 根据数据结构类型执行操作
        if (operationData != null) {
            // 统一处理所有操作
            if (finalOperation == OperationType.SELECT_BY_ID) {
                executeSingleOperation(finalOperation, operationData, modelClass);
            }
            if (finalOperation == OperationType.DELETE_BY_ID) {
                executeSingleOperation(finalOperation, operationData, modelClass);
            } else if (operationData.getClass().isArray()) {
                executeBatchOperation(finalOperation, Arrays.asList((Object[]) operationData), modelClass);
            } else if (operationData instanceof Collection) {
                executeBatchOperation(finalOperation, (List<?>) operationData, modelClass);
            } else {
                executeSingleOperation(finalOperation, operationData, modelClass);
            }
        }

        return result;
    }

    /**
     * 解析请求体为强类型对象/数组
     */
    private static Object parseRequestPayload(HttpServletRequest request, Class<?> modelClass) {
        String requestJson = getRequestJson(request);
        if (StrUtil.isBlank(requestJson)) return null;

        try {
            // 尝试解析整个请求体
            Object parsed = JSON.parse(requestJson);

            // 处理数组类型数据
            if (parsed instanceof JSONArray) {
                JSONArray array = (JSONArray) parsed;
                return parseJsonArray(array, modelClass);
            }
            // 处理单对象类型数据
            else if (parsed instanceof JSONObject) {
                return parseJsonObject(requestJson, modelClass);
            }
            // 处理基本类型值或单值
            else {
                return parseSingleValue(parsed, modelClass);
            }
        } catch (Exception e) {
            throw new RuntimeException("请求数据解析失败: " + requestJson, e);
        }
    }

    /**
     * 解析JSON数组（支持对象数组和基本类型数组）
     */
    private static Object parseJsonArray(JSONArray array, Class<?> modelClass) {
        if (array.isEmpty()) {
            return Collections.emptyList();
        }

        // 检查第一个元素的类型
        Object firstElement = array.get(0);

        // 情况1：数组中是对象类型
        if (firstElement instanceof JSONObject) {
            List<Object> objects = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject json = array.getJSONObject(i);
                objects.add(JSON.parseObject(json.toJSONString(), modelClass));
            }
            return objects;
        }
        // 情况2：数组中是基本类型（如字符串、数字）
        else {
            return createIdModelList(array, modelClass);
        }
    }

    /**
     * 解析JSON对象
     */
    private static Object parseJsonObject(String requestJson, Class<?> modelClass) {
        try {
            // 1. 尝试作为完整对象解析
            return JSON.parseObject(requestJson, modelClass);
        } catch (Exception e) {
            // 2. 回退处理：可能为简单值
            return parseSingleValue(requestJson, modelClass);
        }
    }

    /**
     * 解析单值（非数组非对象）
     */
    private static Object parseSingleValue(Object value, Class<?> modelClass) {
        // 如果直接是模型类型实例
        if (modelClass.isInstance(value)) {
            return value;
        }

        // 尝试创建模型实例并设置值
        try {
            // 1. 识别ID字段
            Field idField = getPrimaryKeyField(modelClass);
            if (idField == null) {
                throw new RuntimeException("模型类缺少主键字段: " + modelClass.getName());
            }

            // 2. 创建模型实例
            Object model = modelClass.getDeclaredConstructor().newInstance();

            // 3. 转换值并设置
            Class<?> idType = idField.getType();
            Object convertedValue = convertIdValue(value, idType);

            idField.setAccessible(true);
            idField.set(model, convertedValue);

            return model;
        } catch (Exception e) {
            throw new RuntimeException("基于值创建模型失败: " + value, e);
        }
    }

    /**
     * 更智能的类型转换器
     */
    private static Object convertIdValue(Object rawValue, Class<?> targetType) {
        if (rawValue == null) return null;

        String stringValue = rawValue.toString();

        // 特殊类型处理
        if (targetType == String.class) {
            return stringValue;
        } else if (targetType == Long.class || targetType == long.class) {
            try {
                return Long.parseLong(stringValue);
            } catch (NumberFormatException e) {
                // 尝试处理包含非数字字符的ID
                return stringValue.replaceAll("[^0-9]", "");
            }
        } else if (targetType == Integer.class || targetType == int.class) {
            try {
                return Integer.parseInt(stringValue);
            } catch (NumberFormatException e) {
                // 清理非数字字符
                return Integer.parseInt(stringValue.replaceAll("[^0-9]", ""));
            }
        } else if (targetType == Boolean.class || targetType == boolean.class) {
            return Boolean.parseBoolean(stringValue);
        } else if (targetType == LocalDateTime.class) {
            try {
                return LocalDateTime.parse(stringValue, DateTimeFormatter.ISO_DATE_TIME);
            } catch (Exception e) {
                // 尝试多种格式解析
                return tryParseDate(stringValue);
            }
        }

        // 默认尝试JSON解析
        try {
            return JSON.parseObject(JSON.toJSONString(rawValue), targetType);
        } catch (Exception e) {
            return rawValue;
        }
    }

    /**
     * 多种日期格式解析
     */
    private static LocalDateTime tryParseDate(String dateStr) {
        DateTimeFormatter[] formatters = {
                DateTimeFormatter.ISO_DATE_TIME,
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
                DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
                DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"),
                DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
        };

        for (DateTimeFormatter formatter : formatters) {
            try {
                return LocalDateTime.parse(dateStr, formatter);
            } catch (DateTimeParseException ignored) {}
        }

        // 无法解析时返回当前时间
        return LocalDateTime.now();
    }

    /**
     * 创建只包含ID字段的模型列表
     */
    private static List<?> createIdModelList(JSONArray idArray, Class<?> modelClass) {
        try {
            // 1. 查找主键字段
            Field idField = getPrimaryKeyField(modelClass);
            if (idField == null) {
                throw new RuntimeException("模型类缺少主键字段: " + modelClass.getName());
            }

            // 2. 获取主键字段类型
            Class<?> idType = idField.getType();

            // 3. 创建实例列表
            List<Object> models = new ArrayList<>(idArray.size());
            Constructor<?> constructor = modelClass.getDeclaredConstructor();
            constructor.setAccessible(true);

            for (int i = 0; i < idArray.size(); i++) {
                // 4. 创建模型实例
                Object model = constructor.newInstance();

                // 5. 设置主键值（带类型转换）
                Object idValue = idArray.get(i);
                Object convertedValue = convertIdValue(idValue, idType);

                idField.setAccessible(true);
                idField.set(model, convertedValue);

                models.add(model);
            }
            return models;
        } catch (Exception e) {
            throw new RuntimeException("基于ID创建模型列表失败", e);
        }
    }

    /**
     * 执行单对象操作
     */
    private static void executeSingleOperation(OperationType operation,
                                               Object model,
                                               Class<?> modelClass) {
        switch (operation) {
            case SAVE:
                Model.save(model);
                break;
            case UPDATE:
                Model.update(model);
                break;
            case UPDATE_SELECTIVE:
                Model.updateSelective(model);
                break;
            case DELETE:
                // 智能删除：根据对象主键自动识别
                executeSmartDelete(model, modelClass);
                break;
        }
    }

    /**
     * 执行批量操作（支持数组和集合）
     */
    private static void executeBatchOperation(OperationType operation,
                                              List<?> models,
                                              Class<?> modelClass) {
        if (models == null || models.isEmpty()) return;

        switch (operation) {
            case SAVE:
            case SAVE_BATCH:
                executeSaveBatch(models);
                break;
            case UPDATE:
            case UPDATE_BATCH:
                Model.updateBatch(models);
                break;
            case DELETE:
            case DELETE_BY_IDS:
                executeBatchDelete(models, modelClass);
                break;
        }
    }

    private static void executeSaveBatch(List<?> models) {
        if (models == null || models.isEmpty()) return;

        try {
            // 获取第一个模型实例及其Class类型
            Object model = models.get(0);
            Class<?> tClass = model.getClass();

            // 从缓存中获取删除字段
            List<Field> deleteFields = ORMUtils.getDeleteFields(tClass);

            // 构建删除条件（优化：避免不必要的字符串拼接）
            QueryOperator deleteCondition = QueryOperator.empty();
            for (Field field : deleteFields) {
                Object value = field.get(model);
                if (value != null) {
                    deleteCondition = deleteCondition.eq(field.getName(), value);
                }
            }

            // 执行批量删除（只有存在删除字段时才执行）
            if (!deleteFields.isEmpty()) {
                // 这里需要保证对应的DELETE语句在事务范围内执行
                Model.delete(deleteCondition, tClass);
            }

            // 批量保存（建议使用批处理）
            Model.saveBatch(models);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to access delete field", e);
        }
    }

    /**
     * 智能删除（基于主键值）
     */
    private static void executeSmartDelete(Object model, Class<?> modelClass) {
        try {
            // 自动识别ID字段（优先找@Id注解字段，其次找"id"字段）
            Field idField = getPrimaryKeyField(modelClass);
            if (idField != null) {
                idField.setAccessible(true);
                Object idValue = idField.get(model);
                if (idValue != null) {
                    Model.deleteById(idValue, modelClass);
                }
            }
            // 条件查询
            List<Field> allFields = getAllFields(modelClass);
            QueryOperator<Object> query = QueryOperator.empty();
            for (Field field : allFields) {
                field.setAccessible(true);
                if (Objects.nonNull(field.get(model))) {
                    query = query.eq(field.getName(), field.get(model));
                }
            }
            Class<Object> objectClass = (Class<Object>) modelClass;
            Model.delete(query, objectClass);
        } catch (Exception e) {
            throw new RuntimeException("删除操作失败", e);
        }
    }

    /**
     * 批量删除（基于主键）
     */
    private static void executeBatchDelete(List<?> models, Class<?> modelClass) {
        try {
            Field idField = getPrimaryKeyField(modelClass);
            if (idField != null) {
                List<Object> ids = models.stream()
                        .map(model -> {
                            try {
                                idField.setAccessible(true);
                                return idField.get(model);
                            } catch (Exception e) {
                                return null;
                            }
                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                if (!ids.isEmpty()) {
                    Class<Object> objectClass = (Class<Object>) modelClass;
                    Model.deleteByIds(ids, objectClass);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("批量删除失败", e);
        }
    }

    /**
     * 处理扩展API（安全+高性能）
     */
    private static DataResult processExtendedApi(HttpServletRequest request, String url) {
        DataResult result = new DataResult();

        // 使用缓存获取API配置
        RequestMethodAndUrl apiConfig = API_URL_CACHE.computeIfAbsent(url, k ->
                findMatchingApiConfig(url)
        );

        if (apiConfig == null) {
            return result;
        }

        List<FieldParam> params = getRequestFieldParams(request);
        String contentType = request.getContentType();

        // 安全设置请求体类型
        if (APPLICATION_JSON.equals(contentType)) {
            apiConfig.setBodyType(0);
            // 安全JSON序列化
            apiConfig.setArgs(new Object[]{toSafeJsonString(params)});
        } else if (contentType != null && contentType.startsWith("multipart/form-data")) {
            apiConfig.setBodyType(1);
            apiConfig.setArgs(params.toArray());
        }

        // 安全调用API
        Object apiResult = invokeHttpRequest(apiConfig);
        result.setData(apiResult);
        return result;
    }

    // ==================== 工具方法（安全+高性能） ====================

    /**
     * 从URL中提取类名（安全处理）
     */
    private static String extractClassName(String path) {
        if (path == null || path.isEmpty()) return "";

        int lastSlash = path.lastIndexOf('/');
        return lastSlash != -1 ? path.substring(lastSlash + 1) : "";
    }

    /**
     * 从URL中提取ID（安全处理）
     */
    private static String extractIdFromUrl(String url, OperationType operation) {
        if (operation != OperationType.SELECT_BY_ID) return "";

        int start = url.indexOf(SELECT_BY_ID_PATH) + SELECT_BY_ID_PATH.length() + 1;
        if (start >= url.length()) return "";

        // 安全分割URL
        String[] parts = url.substring(start).split("/");
        return parts.length > 0 ? parts[0] : "";
    }

    /**
     * 构建安全查询条件（防止SQL注入）
     */
    private static QueryOperator buildSafeQueryOperator(List<FieldParam> params, OperationType operation) {
        QueryOperator query = QueryOperator.empty();

        // 使用流式处理优化性能
        for (FieldParam param : params) {
            String field = uncapUnderline(param.getName());
            Object value = param.getValue();

            // 安全过滤特殊字符
            if (value instanceof String) {
                value = sanitizeString((String) value);
            }

            // 根据操作类型构建查询
            if (operation == OperationType.SELECT_ONE) {
                query = query.eq(field, value);
            } else {
                query = query.like(field, value);
            }
        }
        return query;
    }

    /**
     * 执行查询操作（安全+高性能）
     */
    private static Object executeQueryOperation(OperationType operation, QueryOperator query,
                                                Class<?> modelClass, List<FieldParam> params,
                                                String id) {
        switch (operation) {
            case SELECT_ONE:
                return Model.selectOne(query, modelClass);
            case SELECT_PAGE:
                int pageNum = params.stream()
                        .filter(param -> Objects.equals(PAGE_NUM_PARAM, param.getName()))
                        .map(FieldParam::getValue).map(Objects::toString).map(Integer::parseInt)
                        .findFirst().orElse(DEFAULT_PAGE_NUM);
                int pageSize = params.stream()
                        .filter(param -> Objects.equals(PAGE_SIZE_PARAM, param.getName()))
                        .map(FieldParam::getValue).map(Objects::toString).map(Integer::parseInt)
                        .findFirst().orElse(DEFAULT_PAGE_SIZE);
                return Model.selectPage(pageNum, pageSize, query, modelClass);
            case SELECT_CURSOR_PAGE:
                return getCursorPageResult(query, modelClass, params);
            case SELECT_LIST:
                return Model.select(query, modelClass);
            case SELECT_BY_ID:
                // 安全校验ID
                if (StrUtil.isBlank(id)) return null;
                return Model.selectById(id, modelClass);
            default:
                return null;
        }
    }

    // 获取游标分页结果
    private static PageResult<?> getCursorPageResult(QueryOperator query, Class<?> modelClass, List<FieldParam> params) {
        String nextCursor = params.stream()
                .filter(param -> Objects.equals(NEXT_CURSOR_PARAM, param.getName()))
                .map(FieldParam::getValue).map(String::valueOf)
                .findFirst().orElse(null);
        Integer pageSize = params.stream()
                .filter(param -> Objects.equals(PAGE_SIZE_PARAM, param.getName()))
                .map(FieldParam::getValue).map(String::valueOf).map(Integer::parseInt)
                .findFirst().orElse(DEFAULT_PAGE_SIZE);
        Boolean orderByDesc = params.stream()
                .filter(param -> Objects.equals(ORDER_BY_DESC, param.getName()))
                .map(FieldParam::getValue).map(String::valueOf).map(Boolean::valueOf)
                .findFirst().orElse(true);
        return Model.selectCursorPage(pageSize, nextCursor, orderByDesc, query, modelClass);
    }

    /**
     * 查找匹配的API配置（高性能）
     */
    private static RequestMethodAndUrl findMatchingApiConfig(String url) {
        return getExtendApiUrls().stream()
                .filter(api -> url.contains(api.getUrl()))
                .findFirst()
                .orElse(null);
    }

    // ==================== 安全工具方法 ====================

    /**
     * 安全转换整数（防攻击）
     */
    private static int parseInt(String value, int defaultValue) {
        if (value == null || value.isEmpty()) return defaultValue;

        // 防止超大数字攻击
        if (value.length() > 10) return defaultValue;

        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * 安全JSON序列化（防JSON炸弹）
     */
    private static String toSafeJsonString(List<FieldParam> params) {
        // 限制最大长度
        if (params.size() > 100) {
            return "{}";
        }

        // 安全序列化
        return JSON.toJSONString(params);
    }

    /**
     * 字符串安全过滤（防注入）
     */
    private static String sanitizeString(String input) {
        if (input == null) return null;

        // 过滤危险字符
        return input.replaceAll("[\"'\\\\;]", "");
    }

    /**
     * 判断是否快速模式路径（高性能）
     */
    public static boolean isFastModePath(String path) {
        if (path == null || path.isEmpty()) return false;

        // 使用并行流提高性能
        return Arrays.stream(path.split("/"))
                .anyMatch(segment -> PATH_OPERATIONS.containsKey("/" + segment));
    }

}